using BuildingBlocks.Abstractions.Permissions;
using Grpc.Net.Client;
using PermissionCenter.Grpc;

namespace Catalog.Infrastructure.GrpcClients
{
    public class PermissionCenterGrpcClient: IPermissionCenterClient
    {
        private readonly PermissionCenter.Grpc.PermissionCenter.PermissionCenterClient _permissionClient;

        public PermissionCenterGrpcClient(string permissionCenterUrl)
        {
            // 本地开发信任自签名证书
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
            };

            // gRPC Channel for PermissionCenter
            var permissionChannel = GrpcChannel.ForAddress(permissionCenterUrl, new GrpcChannelOptions
            {
                HttpHandler = handler
            });
            _permissionClient = new PermissionCenter.Grpc.PermissionCenter.PermissionCenterClient(permissionChannel);
        }

        public async Task<bool> UserHasPermissionAsync(string userId, string permissionKey)
        {
            var reply = await _permissionClient.UserHasPermissionAsync(new UserPermissionRequest
            {
                UserId = userId,
                PermissionKey = permissionKey
            });

            return reply.HasPermission;
        }
    }
}